package com.example.demoratelimit.ratelimit;


import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Calendar;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@SpringBootTest
public class DemoConsumer {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String KEY = "rate_limit_list";

    private static volatile RateLimiter limiter = RateLimiter.create(5);

    @Test
    public void testConsumer() {
        String KEYkey = "rate_limit_list";

        ExecutorService executorService = Executors.newFixedThreadPool(5);

        while (true) {
            Long size = redisTemplate.opsForList().size(KEY);
            if(size % 100 == 0) {
                log.info("============= working ==============");
            }
            if(size == 0) {
                break;
            }


            limiter.acquire();
            pop(limiter);
//            executorService.submit(new Runnable() {
//                @Override
//                public void run() {
//                    while (true) {
//                        if(size != 0) {
//                            pop(limiter);
//                        }
//                        break;
//                    }
//                }
//
//            });

        }
    }

    public void pop(RateLimiter limiter) {
        //...发送请求
        String result = (String) redisTemplate.opsForList().rightPop(KEY);
        log.info(result + ":" + Calendar.getInstance().getTimeInMillis());
    }

}


